package com.along.currentlimiting.redis.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/*
 * @Author: liujinyi
 * @DateTime: 2025/2/17 17:51
 */
@Service
public class RedisRateLimiterService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public boolean tryAcquire(String key, int limit, int timeout) {
        Long count = redisTemplate.opsForValue().increment(key, 1);
        if (count != null && count == 1) {
            redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
        }
        return count != null && count <= limit;
    }
}
